const {get} = require('http')

function watchREQUEST(option) {
    const defaultOption = {port: 3078, interval: 1000, url: 'http://localhost', callback: null}
    const port = option.port || defaultOption.port
    const interval = option.interval || defaultOption.interval
    const url = option.url || defaultOption.url
    const callback = option.callback || defaultOption.callback
    const startDate = new Date().valueOf()
    return new Promise((resolve, reject) => {
        const intactURL = `${url}:${port}`
        let timer = setInterval(() => {
            get(
                intactURL,
                function (res) {
                    console.log(`ready is ${intactURL}`)
                    console.log(`elapsed time is ${new Date().valueOf() - startDate}ms 前台项目已打开`)
                    console.log('准备启动主进程')
                    clearInterval(timer)
                    timer = null
                    resolve(true)
                }
            ).on('error', function (err) {
                callback && callback({
                    err: err,
                    timer: timer
                })
                console.log('未获取响应，监控中')
            })

        }, interval)
    })
}

module.exports.watchREQUEST = watchREQUEST